import { Config } from './config.js'

class Token {
	constructor() {
		this.verifyUrl = Config.api_base_url + '/token/verify'
		this.tokenUrl = Config.api_base_url + '/token'
	}

	verify() {
		const token = uni.getStorageSync('token')
		if (!token) {
			this.getTokenFromServer()
		} else {
			this._verifyTokenFromServe(token)
		}
	}

	getTokenFromServer(callback) {
		let that = this
		uni.login({
			success: function(res) {
				
				uni.request({
					url: that.tokenUrl,
					method: 'POST',
					data: {
						code: res.code
					},
					success: function(res) {
						uni.setStorageSync('token', res.data.token)
						uni.setStorageSync('scope', res.data.scope ? res.data.scope : 0)
						callback && callback(res.data.token)
					}
				})
			}
		})
	}

	_verifyTokenFromServe(token) {
		let that = this
		uni.request({
			url: that.verifyUrl,
			method: 'POST',
			data: {
				token: token
			},
			success: function(res) {
				var valid = res.data.isValid;
				if (!valid) {
					that.getTokenFromServer();
				} else {
					uni.setStorageSync('scope', res.data.scope)
				}
			}
		})
	}
}
export {
	Token
}
